#include "ConfigManager.h"
#include <sstream>
#include <fstream>
using namespace OOPUtils;
using namespace std;


ConfigManager::ConfigManager ()
{

}



OOPPtr< Config > OOPUtils::ConfigManager::load (const OOPString & filePath)
		throw (ReadConfigFileException)
{
	OOPString loadPath = _basePath + filePath;
	wifstream fileReader (loadPath.c_str ());
	if (!fileReader)
		OOPTHROW (ReadConfigFileException);
	OOPPtr< Config > pConfig = new Config ();
	while (!fileReader.eof ()) {
		OOPString anItem;
		getline (fileReader, anItem);
		if (fileReader.fail () || fileReader.bad ())
			OOPTHROW (ReadConfigFileException);
		int separator = anItem.find_first_of (L'=');
		if (separator == -1)
			OOPTHROW (ReadConfigFileException);
		OOPString attrName = anItem.substr (0, separator);
		OOPString attrValue = anItem.substr (separator + 1);
		pConfig->_attrs.insert (make_pair (attrName, attrValue));
	}
	pConfig->setFilePath (loadPath);
	return pConfig;
}



void OOPUtils::ConfigManager::save (OOPPtr< Config > pConfigToSave,
		const OOPString & filePath) throw (WriteConfigFileException)
{
	OOPString savePath;
	if (filePath == OOPString ())
		savePath = pConfigToSave->getFilePath ();
	else
		savePath = _basePath + filePath;

	wofstream fileWriter (savePath.c_str ());
	if (!fileWriter)
		OOPTHROW (WriteConfigFileException);
	for (map< OOPString, OOPString >::iterator iter =
			pConfigToSave->_attrs.begin (); iter != pConfigToSave->
			_attrs.end (); ++iter)
		if (iter->second != OOPString ())
			fileWriter << iter->first << "=" << iter->second << endl;
	if (fileWriter.bad () || fileWriter.fail ())
		OOPTHROW (WriteConfigFileException);
}

void OOPUtils::ConfigManager::setBasePath (const OOPString& basePath)
{
	_basePath = basePath;
}

OOPString& OOPUtils::ConfigManager::getBasePath ()
{
	return _basePath;
}

const OOPString& OOPUtils::ConfigManager::getBasePath () const
{
	return _basePath;
}